const heroesModel = require('../model/HeroesModel');
const moment = require('moment');

class HeroesService {
  //查找全部英雄
  async getHeroes(req, res, next) {
    try {
      const {results} = await heroesModel.findAll();
      if (results.length === 0) return res.json({err_code: 1, message: '未查询到相关数据'});
      res.json({err_code: 0, message: results});
    } catch (e) {
      res.json({err_code: 1, message: "意外错误" + e});
    }
  }

  //根据id查找英雄
  async getHeroesById(req, res, next) {
    const id = req.params.id;
    try {
      const {results} = await heroesModel.findById(id);
      if (results.length === 0) return res.json({err_code: 1, message: '该英雄数据不存在'});
      res.json({
        err_code: 0,
        message: results
      })
    } catch (e) {
      res.json({err_code: 1, message: "意外错误" + e});
    }
  }

  //根据id编辑英雄
  async updateHeroes(req, res, next) {
    const id = req.params.id;
    const body = req.body;
    try {
      const {results} = await heroesModel.update(body, id);
      if (results.affectedRows !== 1) return res.json({err_code: 1, message: '英雄编辑失败'})
      res.json({
        err_code: 0,
        message: "英雄编辑成功"
      })
    } catch (e) {
      res.json({err_code: 1, message: "意外错误" + e});
    }
  }

  //根据id删除英雄
  async deleteHeroes(req, res, next) {
    const id = req.params.id;
    try {
      const {results} = await heroesModel.delete(id);
      if (results.affectedRows !== 1) return res.json({err_code: 1, message: '英雄删除失败'})
      res.json({
        err_code: 0,
        message: "英雄删除成功"
      })
    } catch (e) {
      res.json({err_code: 1, message: "意外错误" + e});
    }
  }

  //添加英雄
  async addHeroes(req, res, next) {
    const body = req.body;
    body.ctime = moment().format('YYYY-MM-DD HH:mm:ss');

    const name = body.name;
    try {
      //先判断是否已经存在该数据
      const isExist = await heroesModel.findIsExist(name);
      if (isExist.results.length >= 1) return res.json({err_code: 1, message: '该英雄已存在'})
      //判断是否是第一次添加该数据
      const isFirst = await heroesModel.findByName(name);
      //不是第一次创建就用create创建,否则用restore设置数据status为1
      let result;
      if (isFirst.results.length >= 1) {
        result = await heroesModel.restore(body, isFirst.results[0].id);
      } else {
        result = await heroesModel.create(body);
      }
      if (result.results.affectedRows !== 1) return res.json({err_code: 1, message: '添加英雄失败'})
      res.json({
        err_code: 0,
        message: "添加英雄成功"
      });
    } catch (e) {
      res.json({err_code: 1, message: "意外错误" + e});
    }
  }
}

module.exports = new HeroesService();